package com.dmai.capacity.platform.common.utils;


import javax.servlet.http.HttpServletRequest;

import com.dmai.capacity.platform.common.model.BaseUser;
import com.dmai.capacity.platform.common.service.IUserBaseService;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.dmai.capacity.platform.common.constant.SecurityConstants;

import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;

/**
 * 获取当前登录人工具类
 */
@UtilityClass
public class UserUtils {
    /**
     * 获取当前登录人
     */
    public BaseUser getCurrentUser(HttpServletRequest request, boolean isFull) {
        BaseUser user = null;

        //强一致性校验
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            //客户端模式只返回一个clientId
            if (principal instanceof BaseUser) {
                user = (BaseUser) principal;
            }
        }
        //弱校验
        if (user == null) {
            String userId = request.getHeader(SecurityConstants.USER_ID_HEADER);
            String username = request.getHeader(SecurityConstants.USER_HEADER);
            String roles = request.getHeader(SecurityConstants.ROLE_HEADER);

            if (StrUtil.isAllNotBlank(username, userId)) {
                if (isFull) {
                    IUserBaseService userFeignClient = SpringUtil.getBean(IUserBaseService.class);
                    user = userFeignClient.selectByUsername(username);
                } else {
                    user = new BaseUser();
                    user.setId(Long.valueOf(userId));
                    user.setUsername(username);
                }
            }
        }
        return user;
    }
}